package zip;

import com.github.luben.zstd.ZstdInputStream;
import com.github.luben.zstd.ZstdOutputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ZstdUtils {

    public static byte[] compress(String data) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ZstdOutputStream zstdOutputStream = new ZstdOutputStream(outputStream)) {
            zstdOutputStream.write(data.getBytes());
            zstdOutputStream.flush();
            return outputStream.toByteArray();
        }
    }

    public static String decompress(byte[] compressedData) throws IOException {
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(compressedData);
             ZstdInputStream zstdInputStream = new ZstdInputStream(inputStream);
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = zstdInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toString();
        }
    }
}
